import crypto from 'crypto';
import moment from 'moment';

export default {
    /** 分页返回值 */
    resData: {
        count: 0,
        rows: [],
    },

    /**
     * 生成密码
     * @param {*} password
     * @returns
     */
    generatePwd: (password, digest = 'hex') => {
        //密码加密
        password = password + 'www_test_@#$%';
        return crypto.createHash('md5').update(password).digest(digest);
    },

    /**
     * 获取数据类型
     * @param {object} o 参数
     */
    getType: (o) => {
        const getType = Object.prototype.toString.call(o);
        switch (getType) {
            case '[object String]':
                return 'isString';
            case '[object Number]':
                return 'isNumber';
            case '[object Array]':
                return 'isArray';
            case '[object Boolean]':
                return 'isBoolean';
            case '[object Null]':
                return 'isNull';
            case '[object Undefined]':
                return 'isUndefined';
            case '[object Object]':
                return 'isObject';
            case '[object Function]':
                return 'isFunction';
            default:
                break;
        }
    },

    /**
     * 参数验证
     * @param {*} arr 数据库字段
     * @param {*} params 要剔除参数的对象
     */
    verifyParams: (arr, params) => {
        let key = null;
        for (let o in params) {
            // 剔除数据库没有字段
            key = arr.filter((x) => o == x)[0];
            if (!key) {
                delete params[o];
            }
            key = null;
        }
    },

    /**
     * 获取订单号
     * @param {*} id
     * @returns
     */
    getOrderId(id) {
        let n = 5;
        if (id) {
            id = String(id).padEnd(n, 0);
        } else {
            id = this.getNumber(n);
        }
        return `${id}${moment().valueOf()}`;
    },

    /**
     * 随机数
     * @param {*} n
     * @returns
     */
    getNumber(n) {
        return (Math.floor(Math.random() * '1'.padEnd(n + 1, 0)) + '').padEnd(n, 0);
    },
    /**
     * 生成订单号
     */
    markOrderId() {
        return `${Math.ceil(Date.now() / 1000)}${crypto.randomBytes(6).toString('hex').slice(0, 6)}`;
    },
    sleep(ms) {
        return new Promise((resolve) => {
            setTimeout(resolve, ms);
        });
    },
};
